package com.lw.leetcode.linked.b;

import com.lw.leetcode.linked.ListNode;

/**
 * Created with IntelliJ IDEA.
 * 61. 旋转链表
 *
 * @author liw
 * @version 1.0
 * @date 2021/11/1 16:50
 */
public class RotateRight {
    public ListNode rotateRight(ListNode head, int k) {
        if (k == 0 || head == null) {
            return head;
        }
        ListNode a = head;
        int n = 1;
        while (a.next != null) {
            n++;
            a = a.next;
        }
        if (n == 1) {
            return head;
        }
        int limit = k % n;
        if (limit == 0) {
            return head;
        }
        a.next = head;
        ListNode b = head;
        int item = 1;
        limit = n - limit;
        while (item != limit) {
            item++;
            b = b.next;
        }
        ListNode next = b.next;
        b.next = null;
        return next;
    }
}
